const app = getApp()
let util = require('../../utils/util.js') 
const middleware = require('../../utils/middleware.js')
import * as API_Trade from '../../api/trade'
import regeneratorRuntime from '../../lib/wxPromise.min.js'
import { RegExp, Foundation } from '../../ui-utils/index'

Page({
    data: {
      /** 购物车商品列表 */
      shopList: [],
      /** sku列表 */
      skuList:[],
      /* 选中商品数量 */
      checkedCount: 0,
      /* 所有商品数量 */
      allCount: 0,
      /** 购物车总计清单 */
      cartTotal: {},

      /** 当前操作的输入框的值【变化之前】 */
      current_input_value: 1,
      activity_options: [],
      sku_checkout:[],
      promotions_checkout:'',
      showActivityActionsheet: false,
      cur_sku_id: null,
      /** 是否全选 */
      all_checked: false,
      delBtnWidth: 120,
      finished:false
    },
    // 页面初始化 options为页面跳转所带来的参数
    onLoad(options) {
      this.initEleWidth();
    },
    onShow(){
      if (wx.getStorageSync("refresh_token")){
        this.getCartList()
      }else{
        this.setData({ shopList: [], finished: true})
      }
    },

    // 获取购物车数据
    async getCartList() {
      const { cart_list, total_price } = await API_Trade.getCarts()
      this.setData({ finished:true})
      let _checkedCount = 0
      let _allCount = 0
      const _skuList = []
      cart_list.forEach(shop => {
        shop.sku_list.forEach(item => {
          if (item.invalid !== 1) _allCount += item.num
          if (item.checked && item.invalid !== 1) _checkedCount += item.num
          item.purchase_price = Foundation.formatPrice(item.purchase_price)
          if (!item.skuName) item.skuName = this.formatterSkuSpec(item)
        })
        _skuList.push(...shop.sku_list)
      })
      // 数据处理
      total_price.total_price = Foundation.formatPrice(total_price.total_price)
      if (total_price.cash_back !== 0){
         total_price.cash_back = Foundation.formatPrice(total_price.cash_back)
      }
      this.setData({
        shopList: cart_list,
        cartTotal: total_price,
        checkedCount: _checkedCount,
        allCount: _allCount,
        skuList: _skuList
      })
      setTimeout(() => {
        this.setData({ all_checked: this.isCheckedAll() })
      })
    },

    // 判断购物车商品已全选
    isCheckedAll() {
      return !!this.data.checkedCount && this.data.checkedCount === this.data.allCount
    },
    /** 勾选、取消勾选商品 */
    handleCheckSku(e) {
      const sku = e.currentTarget.dataset.sku
      API_Trade.updateSkuChecked(sku.sku_id, sku.checked ? 0 : 1).then(_ => {
        setTimeout(_ => { this.getCartList() }, 200)
      }).catch()
    },
    /** 勾选、取消勾选店铺 */
    handleCheckShop(e) {
      const shop = e.currentTarget.dataset.shop
      API_Trade.checkShop(shop.seller_id, shop.checked ? 0 : 1 ).then(_ => {
        setTimeout(_ => { this.getCartList() }, 200)
      }).catch()
    },
    /** 规格格式化显示 */
    formatterSkuSpec(sku) {
      if (!sku.spec_list || !sku.spec_list.length) return ''
      return sku.spec_list.map(spec => spec.spec_value).join(' - ')
    },
    /** 全选、取消全选 */
    handleCheckAll() {
      API_Trade.checkAll(this.data.all_checked ? 0 : 1).then(_ => {
        setTimeout(_ => { this.getCartList() }, 200)
      }).catch()
    },
    /** 打开促销选择 */
    handleChangeActivity(e) {
      let sku = e.currentTarget.dataset.sku
      const options = sku.single_list.map(item => ({
        name: item.title,
        activity_id: item.activity_id,
        is_check: item.is_check,
        promotion_type: item.promotion_type,
        className: item.is_check === 1 ? 'checked' : '',
        sku
      }))
      const no_act = sku.single_list.filter(item => item.is_check === 1)
      options.push({
        name: '不参加活动',
        className: no_act[0] ? '' : 'checked',
        sku
      })
      this.setData({
        activity_options : options,
        showActivityActionsheet : true,
        cur_sku_id : sku.sku_id
      })
    },
    // 关闭促销选择
    cloneDialog(){
      this.setData({showActivityActionsheet:false})
    },
    
    /** 确认促销选择 */
    handleActivitySelect(e) {
      const item = e.currentTarget.dataset.item
      const { seller_id, single_list = [], sku_id } = item.sku
      if (item.name === '不参加活动') {
        API_Trade.cleanPromotion(seller_id, sku_id).then(() => {
          this.getCartList()
        })
      } else {
        const { promotion_type, activity_id } = item
        const params = {
          seller_id,
          sku_id,
          activity_id,
          promotion_type
        }
        API_Trade.changeActivity(params).then(()=>{
          setTimeout(()=> { this.getCartList() }, 200)
        })
      }
      this.setData({ showActivityActionsheet: false})
    },
    /** 更新商品数量 */
    handleUpdateSkuNum(e) {
      const sku = e.target.dataset.sku
      const symbol = e.target.dataset.symbol
      if (!symbol || typeof symbol !== 'string') {
        if (!e.detail.value) return
        let _num = parseInt(e.detail.value)
        if (isNaN(_num) || _num < 1) {
          wx.showToast({ title: '输入格式有误，请输入正整数',icon:'none' })
          return
        }
        if (_num >= sku.enable_quantity) {
          wx.showToast({ title: '超过最大库存',icon:'none' })
          return
        }
        this.updateSkuNum({sku_id: sku.sku_id, num: _num})
      } else {
        if (symbol === '-' && sku.num < 2) return
        if (symbol === '+' && sku.num >= sku.enable_quantity) {
          wx.showToast({ title: '超过最大库存',icon:'none' })
          return
        }
        let _num = symbol === '+' ? sku.num + 1 : sku.num - 1
        this.updateSkuNum({sku_id: sku.sku_id, num: _num})
      }
    },
    /* 更新sku数据 */
    updateSkuNum(params) {
      setTimeout(() => {
        API_Trade.updateSkuNum(params.sku_id, params.num).then(_ => {
          setTimeout(_ => { this.getCartList() }, 200)
        }).catch()
      }, 200)
    },
    /** 删除 */
    handleDelete: util.throttle(function(e) {
        const sku = e.currentTarget.dataset.sku
        let that = this
        this.data.shopList.forEach(key => { key.sku_list.forEach(item => { item.txtStyle = '' }) })
        this.setData({ shopList: this.data.shopList })
        wx.showModal({
          title: '提示',
          content: '确定要删除这个货品吗?',
          confirmColor:'#f42424',
          success(res) {
            if(res.confirm) {
              API_Trade.deleteSkuItem(sku.sku_id).then(_ => {
                wx.showToast({ title: '删除成功!' })
                setTimeout(_ => { that.getCartList() }, 200)
                that.setData({ current: 0 })
              }).catch()
            }
          }
        })
      }),
      /** 批量删除 */
    handleBatchDelete: util.throttle(function() {
        let that = this
        wx.showModal({
          title: '提示',
          content: '确定要删除这些货品吗?',
          confirmColor: '#f42424',
          success(res) {
            if(res.confirm) {
              const sku_ids = that.data.skuList.filter(item => item.checked).map(item => item.sku_id)
              API_Trade.deleteSkuItem(sku_ids).then(_ => {
                wx.showToast({ title: '删除成功！' })
                setTimeout(_ => { that.getCartList() }, 200)
              }).catch()
            }
          }
        })
      }),
      /** 清空购物车 */
      handleCleanCart() {
        wx.showModal({
          title: '提示',
          content: '确定要清空购物车吗?',
          success(res) {
            if(res.confirm) {
              API_Trade.cleanCarts().then(_ => {
                setTimeout(_ => { this.getCartList() }, 200)
              }).catch()
            }
          }
        })
      },
      /** 去结算 */
    handleCheckout: util.throttle(function() {
      if (!this.data.checkedCount) {
        wx.showToast({title: '您还没有选中商品哦',icon:'none'});
        return false
      }
      wx.navigateTo({
        url: '/pages/shopping/checkout/checkout?way=CART'
      })
    }),

    // 开始滑动事件
    touchS: function (e) {
      if (e.touches.length == 1) {
        this.setData({
          //设置触摸起始点水平方向位置 
          startX: e.touches[0].clientX
        });
      }
    },
    touchM: function (e) {
      if (e.touches.length == 1) {
        //手指移动时水平方向位置 
        var moveX = e.touches[0].clientX;
        //手指起始点位置与移动期间的差值 
        var disX = this.data.startX - moveX;
        var delBtnWidth = this.data.delBtnWidth;
        var txtStyle = "";
        if (disX == 0 || disX < 0) { //如果移动距离小于等于0，文本层位置不变 
          txtStyle = "left:0px";
        } else if (disX > 0) { //移动距离大于0，文本层left值等于手指移动距离 
          txtStyle = "left:-" + disX + "px";
          if (disX >= delBtnWidth) {
            //控制手指移动距离最大值为删除按钮的宽度 
            txtStyle = "left:-" + delBtnWidth + "px";
            //获取手指触摸的是哪一项 
            var shopIndex = e.currentTarget.dataset.shopindex
            var skuIndex = e.currentTarget.dataset.skuindex
            var list = this.data.shopList;
            list.forEach(key => { key.sku_list.forEach(item=>{item.txtStyle = ''})})
            list[shopIndex].sku_list[skuIndex].txtStyle = txtStyle;
            //更新列表的状态 
            this.setData({shopList: list})
          }
        }
      }
    },
    // 滑动中事件
    touchE: function (e) {
      if (e.changedTouches.length == 1) {
        //手指移动结束后水平位置 
        var endX = e.changedTouches[0].clientX;
        //触摸开始与结束，手指移动的距离 
        var disX = this.data.startX - endX;
        var delBtnWidth = this.data.delBtnWidth;
        //如果距离小于删除按钮的1/2，不显示删除按钮 
        var txtStyle = "";
        txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "px" : "left:0px";

        //获取手指触摸的是哪一项 
        var shopIndex = e.currentTarget.dataset.shopindex
        var skuIndex = e.currentTarget.dataset.skuindex
        var list = this.data.shopList;
        list.forEach(key => { key.sku_list.forEach(item => { item.txtStyle = '' }) })
        list[shopIndex].sku_list[skuIndex].txtStyle = txtStyle;
        //更新列表的状态 
        this.setData({ shopList: list })
      }
    },
    //获取元素自适应后的实际宽度 
    getEleWidth: function (w) {
      var real = 0;
      try {
        var res = wx.getSystemInfoSync().windowWidth;
        var scale = (750 / 2) / (w / 2);
        real = Math.floor(res / scale);
        return real;
      } catch (e) {
        return false;
      }
    },
    initEleWidth: function () {
      var delBtnWidth = this.getEleWidth(this.data.delBtnWidth)
      this.setData({delBtnWidth: delBtnWidth})
    },
    // 去购物
    goshopping(){wx.switchTab({url: '/pages/home/home'})}
  })